// 保存token到localStorage
function saveToken(token) {
    localStorage.setItem('jwt_token', token);
}

// 获取token
function getToken() {
    return localStorage.getItem('jwt_token');
}

// 清除token
function clearToken() {
    localStorage.removeItem('jwt_token');
}

// 添加token到请求头
function addAuthHeader(headers = {}) {
    const token = getToken();
    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
    }
    return headers;
}

// 处理登录响应
function handleLoginResponse(response) {
    if (response.code === 200 && response.data.token) {
        saveToken(response.data.token);
        // 获取重定向URL，如果没有则默认到首页
        const urlParams = new URLSearchParams(window.location.search);
        const redirectUrl = urlParams.get('redirect') || '/';
        window.location.href = redirectUrl;
    } else {
        alert(response.message || '登录失败');
    }
}

// 在页面加载时检查认证状态
document.addEventListener('DOMContentLoaded', function() {
    const token = getToken();
    if (token) {
        fetch('/api/auth/check', {
            headers: addAuthHeader()
        })
        .then(response => response.json())
        .then(data => {
            if (data.code !== 200) {
                clearToken();
            }
        })
        .catch(() => {
            clearToken();
        });
    }
}); 